const fs = require('fs')
const path = require('path')
const { exec } = require('child_process')

// 读取当前目录下的 src/lang 目录中的所有 JavaScript 文件
function readLangFiles(langPath, dir) {
  const dirPath = path.join(dir, langPath || 'src/lang/au')
  const files = fs.readdirSync(dirPath)

  const fileContents = {}

  for (const file of files) {
    if (file.endsWith('.js')) {
      const filePath = path.join(dirPath, file)
      const fileContent = fs.readFileSync(filePath, 'utf-8')
      // console.log("gxs --> % readLangFiles % fileContent:\n", fileContent)
      const getFileObject = new Function(fileContent.replace('export default', 'return '))
      fileContents[file.replace('.js', '')] = getFileObject()
    }
  }

  return fileContents
}

function saveLangFiles(langPath, dir, data) {
  const dirPath = path.join(dir, langPath || 'src/lang/au')
  for (const file in data) {
    const filePath = path.join(dirPath, `${file}.js`)
    fs.writeFileSync(filePath, `export default ${JSON.stringify(data[file])}`)
  }

  exec(`prettier --write ${dirPath}`, (error, stdout, stderr) => {
    if (error) {
      console.error(`执行 prettier 命令时出错: ${error} ${stderr}`)
      console.error(`可手动进行格式化文件`)
      return
    }

    console.log('代码已成功格式化并写入文件')
  })
  // prettier . --write
}

module.exports = {
  readLangFiles,
  saveLangFiles,
}
